package com.example.fmgidsprototype.data;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class OpenHelper extends SQLiteOpenHelper{
	
	private Context ctx;

	public OpenHelper(Context ctx) {
		super(ctx, DataConstants.DB_NAME, null, DataConstants.DB_VERSION);
		this.ctx = ctx;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		VenueTable.onCreate(db);
		CategoryTable.onCreate(db);
		VenueCategoryTable.onCreate(db);
		VenueLocationTable.onCreate(db);
		VenueReviewTable.onCreate(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		VenueTable.onUpgrade(db, oldVersion, newVersion);
		CategoryTable.onUpgrade(db, oldVersion, newVersion);
		VenueCategoryTable.onUpgrade(db, oldVersion, newVersion);
	}
	
	public void onOpen(SQLiteDatabase db){
		super.onOpen(db);
	      if (!db.isReadOnly()) {
	         // versions of SQLite older than 3.6.19 don't support foreign keys
	         // and neither do any version compiled with SQLITE_OMIT_FOREIGN_KEY
	         // http://www.sqlite.org/foreignkeys.html#fk_enable
	         // 
	         // make sure foreign key support is turned on if it's there (should be already, just a double-checker)          
	         db.execSQL("PRAGMA foreign_keys=ON;");

	         // then we check to make sure they're on 
	         // (if this returns no data they aren't even available, so we shouldn't even TRY to use them)
	         Cursor c = db.rawQuery("PRAGMA foreign_keys", null);
	         if (c.moveToFirst()) {
	            int result = c.getInt(0);
	         } else {
	            // could use this approach in onCreate, and not rely on foreign keys it not available, etc.
	            // if you had to here you could fall back to triggers
	         }
	         if (!c.isClosed()) {
	            c.close();
	         }
	      }
	}

}
